package com.yuanqi.service.impl;

import com.yuanqi.domain.RetailSalesOrder;
import com.yuanqi.domain.OrderTracking;
import com.yuanqi.domain.CustomerType;
import com.yuanqi.repository.RetailSalesOrderRepository;
import com.yuanqi.repository.OrderTrackingRepository;
import com.yuanqi.service.RetailSalesOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 零售销售订单服务实现类
 */
@Service
@Transactional
public class RetailSalesOrderServiceImpl implements RetailSalesOrderService {
    
    @Autowired
    private RetailSalesOrderRepository retailSalesOrderRepository;
    
    @Autowired
    private OrderTrackingRepository orderTrackingRepository;
    
    @Override
    public RetailSalesOrder createSalesOrder(RetailSalesOrder salesOrder) {
        // 生成订单编码
        if (salesOrder.getOrderCode() == null || salesOrder.getOrderCode().isEmpty()) {
            salesOrder.setOrderCode(generateOrderCode());
        }
        
        salesOrder.setOrderDate(LocalDateTime.now());
        salesOrder.setCreatedAt(LocalDateTime.now());
        salesOrder.setUpdatedAt(LocalDateTime.now());
        
        RetailSalesOrder savedOrder = retailSalesOrderRepository.save(salesOrder);
        
        // 创建订单跟踪记录
        createOrderTracking(savedOrder.getId(), savedOrder.getOrderCode(), "Sales", 
                           "Pending", "订单已创建", "系统", "订单创建成功");
        
        return savedOrder;
    }
    
    @Override
    public RetailSalesOrder updateSalesOrder(RetailSalesOrder salesOrder) {
        salesOrder.setUpdatedAt(LocalDateTime.now());
        return retailSalesOrderRepository.save(salesOrder);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Optional<RetailSalesOrder> findById(Long id) {
        return retailSalesOrderRepository.findById(id);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Optional<RetailSalesOrder> findByOrderCode(String orderCode) {
        return retailSalesOrderRepository.findByOrderCode(orderCode);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<RetailSalesOrder> findAll() {
        return retailSalesOrderRepository.findAll();
    }
    
    @Override
    @Transactional(readOnly = true)
    public Page<RetailSalesOrder> findAll(Pageable pageable) {
        return retailSalesOrderRepository.findAll(pageable);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<RetailSalesOrder> findByCustomerId(Long customerId) {
        return retailSalesOrderRepository.findByCustomerIdOrderByOrderDateDesc(customerId);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<RetailSalesOrder> findByCustomerName(String customerName) {
        return retailSalesOrderRepository.findByCustomerNameContainingOrderByOrderDateDesc(customerName);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<RetailSalesOrder> findByCustomerPhone(String customerPhone) {
        return retailSalesOrderRepository.findByCustomerPhoneOrderByOrderDateDesc(customerPhone);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<RetailSalesOrder> findByOrderStatus(String orderStatus) {
        return retailSalesOrderRepository.findByOrderStatusOrderByOrderDateDesc(orderStatus);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<RetailSalesOrder> findByCustomerType(CustomerType customerType) {
        return retailSalesOrderRepository.findByCustomerTypeOrderByOrderDateDesc(customerType);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<RetailSalesOrder> findByOrderDateBetween(LocalDateTime startDate, LocalDateTime endDate) {
        return retailSalesOrderRepository.findByOrderDateBetween(startDate, endDate);
    }
    
    @Override
    public RetailSalesOrder updateOrderStatus(Long orderId, String status, String operatorName) {
        Optional<RetailSalesOrder> orderOpt = retailSalesOrderRepository.findById(orderId);
        if (!orderOpt.isPresent()) {
            throw new RuntimeException("订单不存在");
        }
        
        RetailSalesOrder order = orderOpt.get();
        String oldStatus = order.getOrderStatus();
        order.setOrderStatus(status);
        order.setUpdatedAt(LocalDateTime.now());
        
        RetailSalesOrder savedOrder = retailSalesOrderRepository.save(order);
        
        // 创建状态变更跟踪记录
        String statusDescription = getStatusDescription(status);
        createOrderTracking(orderId, order.getOrderCode(), "Sales", status, 
                           statusDescription, operatorName, "状态从 " + oldStatus + " 变更为 " + status);
        
        return savedOrder;
    }
    
    @Override
    public RetailSalesOrder processOrder(Long orderId, String operatorName) {
        return updateOrderStatus(orderId, "Processing", operatorName);
    }
    
    @Override
    public RetailSalesOrder shipOrder(Long orderId, String operatorName, String shippingInfo) {
        Optional<RetailSalesOrder> orderOpt = retailSalesOrderRepository.findById(orderId);
        if (!orderOpt.isPresent()) {
            throw new RuntimeException("订单不存在");
        }
        
        RetailSalesOrder order = orderOpt.get();
        order.setOrderStatus("Shipped");
        order.setUpdatedAt(LocalDateTime.now());
        
        RetailSalesOrder savedOrder = retailSalesOrderRepository.save(order);
        
        // 创建发货跟踪记录
        createOrderTracking(orderId, order.getOrderCode(), "Sales", "Shipped", 
                           "商品已发货", operatorName, "商品已发货" + (shippingInfo != null ? " - " + shippingInfo : ""));
        
        return savedOrder;
    }
    
    @Override
    public RetailSalesOrder completeOrder(Long orderId, String operatorName) {
        Optional<RetailSalesOrder> orderOpt = retailSalesOrderRepository.findById(orderId);
        if (!orderOpt.isPresent()) {
            throw new RuntimeException("订单不存在");
        }
        
        RetailSalesOrder order = orderOpt.get();
        order.setOrderStatus("Delivered");
        order.setDeliveryDate(LocalDateTime.now());
        order.setUpdatedAt(LocalDateTime.now());
        
        RetailSalesOrder savedOrder = retailSalesOrderRepository.save(order);
        
        // 创建完成跟踪记录
        createOrderTracking(orderId, order.getOrderCode(), "Sales", "Delivered", 
                           "商品已送达", operatorName, "订单已完成");
        
        return savedOrder;
    }
    
    @Override
    public RetailSalesOrder cancelOrder(Long orderId, String reason, String operatorName) {
        return updateOrderStatus(orderId, "Cancelled", operatorName);
    }
    
    @Override
    public void deleteById(Long id) {
        retailSalesOrderRepository.deleteById(id);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Object getOrderStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        
        // 今日订单数
        Long todayOrders = retailSalesOrderRepository.countTodayOrders();
        statistics.put("todayOrders", todayOrders);
        
        // 本月订单数
        Long monthOrders = retailSalesOrderRepository.countMonthOrders();
        statistics.put("monthOrders", monthOrders);
        
        // 今日销售额
        Double todaySales = retailSalesOrderRepository.sumTodaySales();
        statistics.put("todaySales", todaySales);
        
        // 本月销售额
        Double monthSales = retailSalesOrderRepository.sumMonthSales();
        statistics.put("monthSales", monthSales);
        
        // 待处理订单数
        List<RetailSalesOrder> pendingOrders = retailSalesOrderRepository.findPendingOrders();
        statistics.put("pendingOrders", pendingOrders.size());
        
        // 处理中订单数
        List<RetailSalesOrder> processingOrders = retailSalesOrderRepository.findProcessingOrders();
        statistics.put("processingOrders", processingOrders.size());
        
        // 已发货订单数
        List<RetailSalesOrder> shippedOrders = retailSalesOrderRepository.findShippedOrders();
        statistics.put("shippedOrders", shippedOrders.size());
        
        return statistics;
    }
    
    @Override
    public String generateOrderCode() {
        String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String timeStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HHmmss"));
        return "RSO" + dateStr + timeStr;
    }
    
    /**
     * 创建订单跟踪记录
     */
    private void createOrderTracking(Long orderId, String orderCode, String orderType, 
                                   String status, String statusDescription, String operatorName, String remark) {
        OrderTracking tracking = new OrderTracking();
        tracking.setOrderId(orderId);
        tracking.setStatusType(status);
        tracking.setStatusDescription(statusDescription);
        tracking.setOperatorName(operatorName);
        tracking.setRemark(remark);
        tracking.setTimestamp(LocalDateTime.now());
        
        orderTrackingRepository.save(tracking);
    }
    
    /**
     * 获取状态描述
     */
    private String getStatusDescription(String status) {
        switch (status) {
            case "Pending":
                return "待处理";
            case "Processing":
                return "处理中";
            case "Shipped":
                return "已发货";
            case "Delivered":
                return "已送达";
            case "Cancelled":
                return "已取消";
            default:
                return status;
        }
    }
}
